<template>
    <div class="index-page test">
        <div class="student1">
        	<!-- <router-link to="/home"> -->
         	<el-button type="primary" size="small" @click="$router.back(-1);"  style='margin-left: 5px;'  icon="el-icon-caret-left">返回</el-button>
        <!-- </router-link> -->
            <el-input placeholder="请选择学生" icon="search" v-model="student" class="input" @focus="componentsShow('student')"></el-input>
            <!-- <el-button type="text">缴费记录</el-button> -->

                <el-button type="primary" size="small" @click="componentsShow('course')">购买课程</el-button>
                <el-button type="primary" size="small" @click="componentsShow('xzwp')">购买物品</el-button>

                <!-- <el-dropdown @command="handleCommand" class="mb">
                  <el-button type="success">
                    选择模板<i class="el-icon-caret-bottom el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown" >
                    <el-dropdown-item :command="v.id" v-for="v in mblist">{{v.mc}}</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown> -->

        </div>
        <!-- 数据表格展示区域 -->
        <el-table
            :data="dataList"
            border
            stripe
            align="center"
            class="admin-table"
            sum-text
            :row-class-name="tableRowClassName"
            @select="checkSelect"
            @select-all="checkall">
            <div slot='empty'>
                <img src="../../../assets/img/empty.png" style="width:40px;vertical-align: middle;">
                <span style="vertical-align: middle;">您还没有选择物品哦!</span>
            </div>
            <el-table-column
                :prop="v.prop"
                :label="v.label"
                v-for="(v,index) in portTitleList"
                align="center"
                show-overflow-tooltip
                v-if="v.hide != 0"
                :formatter="v.formatter"
                :align="v.align || 'center'"
                :fixed="v.fixed"
                :class-name="v.columnStyle"
                :width="v.width"
                :min-width="v.minWidth"
                :header-align="v.headerAlign || 'center'"
                >
                <template scope="scope">
                    <div slot="reference" :style="tableCellControl(scope)" v-if="scope.column.property === 'number' ||  scope.column.property === 'zk'">
                        <el-input class="content-input" v-model="scope.row[scope.column.property]" ></el-input>
                        <!-- :disabled="scope.row.type === '物品' && scope.column.property === 'zk' ? true:false" -->
                    </div>
                    <div slot="reference" v-else-if="scope.column.property === 'yj'">
                        {{scope.row.jcjg * scope.row.number * scope.row.zk*1/100 || 0}}
                    </div>
                    <div slot="reference" v-else>
                       {{ scope.row[scope.column.property] }}
                    </div>
                 </template>
            </el-table-column>


            <el-table-column
                label="操作"
                align="center"
                width="100px"
                fixed="right">
                <template scope="scope">
                    <el-button size="small" type="danger" @click="componentsShow(v.type,scope)" v-for="v in portBntList">{{v.name}}</el-button>
                </template>
            </el-table-column>
        </el-table>


        <el-button type="primary" class="submit" @click="jiesuan()" :disabled="accountDisabled">结算</el-button>
        <el-dialog title="结算" :visible.sync="dialogAccounts" :modal-append-to-body='false' lock-scroll size="small" class="dailog">
            <el-table
                :data="dataList"
                border
                stripe
                type="mini"
                align="center"
                class="admin-table"
                sum-text
                :row-class-name="tableRowClassName"
                @select="checkSelect"
                @select-all="checkall">
                <div slot='empty'>
                    <img src="../../../assets/img/empty.png" style="width:40px;vertical-align: middle;">
                    <span style="vertical-align: middle;">您还没有选择物品哦!</span>
                </div>
                <el-table-column
                    :prop="v.prop"
                    :label="v.label"
                    v-for="(v,index) in portTitleList"
                    align="center"
                    show-overflow-tooltip
                    v-if="v.hide != 0"
                    :formatter="v.formatter"
                    :align="v.align || 'center'"
                    :fixed="v.fixed"
                    :class-name="v.columnStyle"
                    :width="v.width"
                    :header-align="v.headerAlign || 'center'"
                    >
                    <template scope="scope">
                        <div slot="reference" v-if="scope.column.property === 'yj'">
                            {{scope.row.jcjg * scope.row.number * scope.row.zk*1/100 || 0}}
                        </div>
                        <div slot="reference" v-else>
                           {{ scope.row[scope.column.property] }}
                        </div>
                     </template>
                </el-table-column>
            </el-table>
            <div class="total">
                <span>课程：￥{{courseTotal}}</span>
                <span>物品：￥{{goodsTotal}}</span>
                <span>合计：￥{{totalAmount}}</span>
            </div>
            <article class="settlement">
                <p>结算</p>
                <div>
                    直减优惠：<input type="text" style="width:100px;" v-model="zj">
                    代金券抵扣：<input type="text" style="width:100px;" v-model="ticket">
                    余额支付：<input style="width:100px;"  type="text" v-model="zfyuer" >（可用余额 {{sjyuer}}）
                    <!-- 实收金额：<input type="text" style="width:100px;" v-model="sum" disabled> -->
                    <!-- 上次余额：<input type="text" style="width:100px;" v-model="sjyuer" disabled> -->

                </div>
            </article>
            <div class="total">
                <span>应交金额：￥{{yjje1}}</span>
                <span>实交金额：￥{{sum}}</span>
                <span>本次预存：￥{{yucun}}</span>
            </div>

            <article class="receiving-account">
                <p>收款账户</p>
                <div>
                    现金：<input type="text" v-model="money.xj">
                    还需交：（￥<span style="color:red;">{{qf1}}</span>）
                    <!-- <input style="width:100px;"  type="text" v-model="qf1" > -->
                    <br/>

                    刷卡：<input type="text" v-model="money.yhzhje">
                    卡号：<input type="text" v-model="money.yhzh">
                    支付宝：<input type="text" v-model="money.zfbzhje">
                    </br>
                    支付备注：<input type="text" v-model="money.zfbzh">
                    微信支付：<input type="text" style="width:150px;" v-model="money.wxzhje">
                    支付备注：<input type="text" style="width:140px;" v-model="money.wxzh">

                    <div class="">
                      微信二维码
                    </div>
                    <div class="">
                      支付宝二维码
                    </div>


                    <!-- 现金：<input type="text" v-model="money.xj">
                    余额支付：<input type="text" v-model="zfyuer" >
                    <span class="space-between"></span>
                    支付宝账号：<input type="text" v-model="money.zfbzh">
                    金额：<input type="text" v-model="money.zfbzhje">
                    <span class="space-between"></span>
                    微信账号：<input type="text" v-model="money.wxzh">
                    金额：<input type="text" v-model="money.wxzhje">
                    <span class="space-between"></span>
                    银行卡账号：<input type="text" v-model="money.yhzh">
                    金额：<input type="text" v-model="money.yhzhje"> -->
                </div>
            </article>

            <el-button type="primary" class="submit" @click="submit">确认购买</el-button>
        </el-dialog>


        <!-- 各个组件显示区域 -->

        <!-- 动画加载 -->
        <LoadingComponent v-show="isLoading"></LoadingComponent>

        <!-- 选择学生组件 -->
        <StudentComponent v-if="portComponents.student.toggle"  @close="componentsHide"  :data="portComponents.student.data"></StudentComponent>

        <!-- 购买课时 -->
        <PayCourse v-if="portComponents.course.toggle"  @close="componentsHide"  :data="portComponents.course.data"></PayCourse>


        <!--<PayArticle v-if="portComponents.article.toggle"  @close="componentsHide"  :data="portComponents.article.data"></PayArticle>-->

        <!-- 单独删除组件 -->
        <DeleteComponent v-if="portComponents.singleDelete.toggle"  @close="componentsHide" :params="portComponents.singleDelete.params" :data="portComponents.singleDelete.data"></DeleteComponent>

		 <!-- 购买物品 -->
		<Xzwplist v-if="portComponents.xzwp.toggle"  @close="componentsHide"  :data="portComponents.xzwp.data"></Xzwplist>


        <!-- 子路由显示区域 -->
        <router-view class="port-view"></router-view>
    </div>
</template>

<script>
    import qs from 'qs'
    import Vue from 'vue'
    import { mapState } from 'vuex'
    import LoadingComponent from 'components/loading'
    import DeleteComponent from './del'
    import StudentComponent from './student'
    import PayCourse from './pay-course'
    import Xzwplist from '../../manage/bs/xzwp'

    export default {
    	props: ['params'],
        components: {
            LoadingComponent,
            DeleteComponent,
            StudentComponent,
            PayCourse,
            Xzwplist
        },
        data () {
            return {
                zj:0,
                student: '',
                studentList: [],
                date: '',
                ticket: 0,
                studentid:"",
                orderid: '',
                mblist:[],
                mblist2:[],
                yuer:'',
                zfyuer:'',
                lx:'',
                dialogAccounts: false,
                // goodsTotal: 0.00,
                // courseTotal: 0.00,
                money: {
                    xj: '',
                    zfbzh: '',
                    zfbzhje: '',
                    wxzh: '',
                    wxzhje: '',
                    yhzh: '',
                    yhzhje: ''


                },
                /*组件区域*/
                portComponents: {
                    singleDelete: {
                        type: 'singleDelete',
                        toggle: false,
                        params: '',
                        data: {
                            index: '',
                            type: 'single',
                            title: '此操作将移除该物品, 是否继续?'
                        }
                    },
                    multipleDelete: {
                        type: 'multipleDelete',
                        toggle: false,
                        params: '',
                        data: {
                            index: '',
                            type: 'multiple',
                            title: '此操作将删除您选中的班级, 是否继续?'
                        }
                    },
                    student : {
                        type: 'student',
                        toggle: false,
                        params: '',
                        data: {}
                    },
                    course : {
                        type: 'course',
                        toggle: false,
                        params: '',
                        data: {}
                    },
                   xzwp : {
        						type: 'xzwp',
        						toggle: false,
        						params: '',
        						data: {}
        						}
                },

                multipleDelNum:'', //获取批量选择的数据
                dataList: [],  //表格数据

                /*
                    prop :  接口参数名
                    label : 接口中文名
                    hide : 是否隐藏这一列
                    align : 这一列对齐顺序 ： left,right,center
                    headerAlign : 这一列表头对齐方式 ： left,right,center
                    formatter: function (row, column) {}
                */
                portTitleList: [
                    {
                        prop:'id',
                        label:'ID',
                        hide:0,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'',
                        headerAlign:'center'
                    },
                    {
                        prop:'type',
                        label:'商品类型',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'100',
                        headerAlign:'center'
                    },
                    {
                        prop:'mc',
                        label:'商品名称',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'100',
                        headerAlign:'center'
                    },
                    {
                        prop:'jcjg',
                        label:'商品价格',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'100',
                        headerAlign:'center'
                    },
                    {
                        prop:'number',
                        label:'购买数量',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'100',
                        headerAlign:'center'
                    },
                    {
                        prop:'yj',
                        label:'应缴费用',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'100',
                        headerAlign:'center'
                    },
                    {
                        prop:'dw',
                        label:'单位',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'100',
                        headerAlign:'center'
                    },
                    {
                        prop:'zk',
                        label:'折扣（%）',
                        hide:1,
                        align:'center',
                        fixed:false,
                        width:'',
                        minWidth:'100',
                        headerAlign:'center'
                    },


                ],
                portBntList: [//接口按钮列表
                    {
                        name:'移除',
                        type:'singleDelete'
                    }
                ],

                /*动画加载*/
                isLoading: true,//动画加载
                searchLoading: false,//搜索按钮触发按钮动画

                /*模糊搜索条件*/
                inputbjmc:'' , //  班级名称,


                /*分页属性设置*/
                layout: 'total, sizes, prev, pager, next, jumper',//组件布局
                pageindex: 1,//当前分页页码
                pagesizes: [12, 24, 36, 72],//显示个数的选择器选项
                pagesize: 12,//每页显示条目数
                total: 0,//总条数


                dropDownData:'', //
            }
        },
        created () {


       // alert(this.$route.query.iid)
	       if (this.$route.query.je==0){
           this.student=this.$route.query.iid;
           this.studentid=this.$route.query.id;
           this.search()
        }else{
          this.student=this.$route.query.iid;
          this.studentid=this.$route.query.id;
        }

            //加载页面时调用
            this.$store.dispatch('changeTitle','物品课程缴费');//修改title
            this.$store.dispatch('changeRouterIndex','/cost/pay');//修改路由

            this.isLoading = true;//动画开始
            // this.muban()
        },
        mounted () {
            this.isLoading = false;//动画结束
        },
        watch:{
            'zfyuer': function(newVal,oldVal){
                if(parseInt(newVal)>=parseInt(this.yuer)) {//如果小于等于零
                    this.zfyuer = this.yuer //恢复原值
                }
            }
        },
        methods: {

          jiesuan(){
            this.dialogAccounts=true
            var logininfo = JSON.parse(localStorage.logininfo) ;
            var params3 = qs.stringify({
              xsid:this.studentid,
              yhid:logininfo.id,
              xxid:logininfo.xxid,
						});
            this.axios.post(this.$store.state.api + 'xs/infoxs',params3 )
            .then( res => {
                this.yuer = res.data[0].yuer
            }).catch( res => {
                console.log(res)
            })
          },
          search(){
            var logininfo = JSON.parse(localStorage.logininfo);
            var params3 = qs.stringify({
              xsid: this.studentid,
              yhid:logininfo.id,
              xxid:logininfo.xxid
						});
            this.axios.post(this.$store.state.api + 'ysbj/kcmx',params3)
            .then( res => {
                this.dataList = res.data.data;
                this.searchLoading = false;
            }).catch( res => {
                this.searchLoading = false;
            })

          },
         //  handleCommand(command) {
         //    var logininfo = JSON.parse(localStorage.logininfo) ;
         //    this.axios.get(this.$store.state.api + 'mbmx/list', {
         //        params: {
         //          yhid:logininfo.id,
         //          xxid:logininfo.xxid,
         //          mbid:command
         //        }
         //    }).then( res => {
         //        this.dataList = res.data.data
         //    }).catch( res => {
         //        console.log(res)
         //    })
         // },
        // muban(){
        //   var logininfo = JSON.parse(localStorage.logininfo) ;
        //   this.axios.get(this.$store.state.api + 'mb/list', {
        //       params: {
        //         yhid:logininfo.id,
        //         xxid:logininfo.xxid,
        //       }
        //   }).then( res => {
        //       // console.log(123)
        //       this.mblist = res.data.data
        //       console.log(this.mblist)
        //   }).catch( res => {
        //       console.log(res)
        //   })
        // },
            tableRowClassName (row, index) {//隔行变色颜色设置
                /*if ( index%4 == 0) {
                    return "table-cell-green";
                }else if( index%4 == 1 ){
                    return "table-cell-yellow";
                }else if( index%4 == 2 ){
                    return "table-cell-red";
                }else{
                    return "table-cell-blue"
                }*/
            },
            tableCellControl (scope) {//表格单元格控制CSS样式
                // console.log(scope)
                /*if (scope.row.id == 112 && scope.column.property == "iname") {
                    return {
                        color:"red",
                    }
                }else{
                    return {
                        color:"green",
                    }
                }*/
            },

            getTime (val) {
                // console.log(val)
                // this.date = val;
                // console.log(this.date)
                this.date = Vue.prototype.$.getLocalTimeAll(new Date(this.date).getTime())
                // console.log(new Date(this.date).getTime())
            },

            submit () {
              this.dialogAccounts = true;
                let promise = new Promise( (resolve, reject) => {
                    var logininfo = JSON.parse(localStorage.logininfo) ;
                    var params3 = qs.stringify({
                      qf:this.qf1,
                      zj:this.zj,
                      yc:this.yucun,
                      zfyuer:this.zfyuer,
                      jsr:logininfo.id,
                      jfr:this.student,
                      zfbzh:this.money.zfbzh,
                      zfbje:this.money.zfbzhje,
                      wxzh:this.money.wxzh,
                      wxje:this.money.wxzhje,
                      yhkzh:this.money.yhzh,
                      yhkje:this.money.yhzhje,
                      xj:this.money.xj,
                      yhj:this.ticket,
                      je:this.sum+'',
                      wpje:this.goodsTotal,
                      kcje:this.courseTotal,
                      xsid:this.studentid,
                      yhid: logininfo.id + '',
                      xxid: logininfo.xxid + '',
                        // yjje:this.totalAmount,
                        // sklx:'收款类型',
                        // skzh:'收款证号'
        						});
                    this.axios.post(this.$store.state.api + 'order/insert',params3)
                    .then( res => {
                        // console.log(res)
                        // console.log(123)
                        resolve(res.data)
                        // location.reload() //刷新页面
                        this.$router.go(-1)
                        // this.dialogAccounts = false;

                    }).catch( res => {
                        console.log(res)
                    })
                })

                promise.then( res => {
                    console.log(res)
                    console.log(211)
                    console.log(this.dataList)
                    this.dataList.forEach( (v, i) => {
                      var params2 = qs.stringify({
                            orderid:res,
                            splx: v.type == '物品' ? 2 : 1,
                            // splx: lx,
                            spid: v.id,
                            jg:this.totalAmount,
                            zk: v.zk,
                            cns: v.number
            						});
                        this.axios.post(this.$store.state.api + 'ordermx/insert',params2)
                        .then( res => {
                            console.log(res)
                        }).catch( res => {
                            console.log(res)
                        })
                    })
                }).catch( res => {
                    console.log(res)
                })
                var jcid = [],
                    zys = 0, //总验收
                    zss = this.courseTotal - this.ticket; //总实收
                this.dataList.forEach( v => {
                    // console.log(v)
                    if (v.type === '课程') {
                        jcid.push(v.id);
                        zys += v.jcjg;
                    }
                })

            },

            checkSelect (selection, row) {//点击单选select触发事件
                console.log(selection, row)
                let strID = [];
                selection.forEach(function(v,i){
                    strID.push(v.id)
                })
                this.multipleDelNum = strID.join(",");
            },
            checkall (selection) {//点击全选select触发事件
                // console.log(selection)
                let strID = [];

                selection.forEach(function(v,i){
                    strID.push(v.id)
                })
                this.multipleDelNum = strID.join(",");
            },

            /* 组件的弹框  */
            componentsShow (type,data) { //显示组件
                console.log(type,data)
                for ( let i in this.portComponents ) {
                    if (type == this.portComponents[i].type) {
                        console.log(this.portComponents[i])

                        this.portComponents[i].toggle = true;
                        this.portComponents[i].params = data;

                        if (this.portComponents[i].data.type == 'single') {
                            this.portComponents[i].data.index = data.row.id

                        }else if(this.portComponents[i].data.type == 'multiple'){
                            this.portComponents[i].data.index = this.multipleDelNum;

                        }else{
                            return;
                        }
                        return;
                    }
                }

            },
            componentsHide (setting) { //关闭组件
                console.log(setting)
                for ( let i in this.portComponents ) {
                    if (setting.type == this.portComponents[i].type) {
                        this.portComponents[i].toggle = false;
                        if (this.portComponents[i].type == 'singleDelete') {
                            this.dataList.splice(setting.index,1)
                        }
                        if (!setting.cancel) {
                           // this.search();
                            if (setting.type == "student") {
                                this.student = setting.data.zwm + ' - ' + setting.data.xh
                                this.studentid = setting.data.id
                            }else{
                                setting.data.forEach( (v) => {
                                   this.dataList.push(v)
                                })

                            }
                        }
                        return;
                    }
                }
            }

        },
        computed: {
          // zfyuer(){
          //   let number = 0.00;
          //   return number
          // },
          qf1(){
            let number = this.yjje1-this.sum
            if(number<=0){
              return 0
            }else{
              return number.toFixed(2)
            }
          //
          },
          sjyuer(){
            if(this.yuer){
              let number = this.yuer - this.zfyuer;
              return number
            }else{
              this.yuer = 0
              let number = this.yuer - this.zfyuer;
              return number
            }
          },
            goodsTotal () { //物品合计
                let number = 0.00;
                for (let i in this.dataList) {
                    if (this.dataList[i].type == '物品') {
                        number += (this.dataList[i].jcjg || 0) * (this.dataList[i].number || 0) * (this.dataList[i].zk*1/100 || 0)
                    }
                }
                return number.toFixed(2)
            },
            courseTotal () { //课时合计
                let number = 0.00;
                for (let i in this.dataList) {
                    if (this.dataList[i].type == '课程') {
                        number += (this.dataList[i].jcjg || 0) * (this.dataList[i].number || 0) * (this.dataList[i].zk*1/100 || 0)
                    }
                }
                return number.toFixed(2)
            },
            yjje1 () { //应交金额
                let number = 0.00;
                number += this.totalAmount - this.zj - this.zfyuer -this.ticket
                // number += this.totalAmount - this.zj - this.zfyuer - this.money.xj - this.money.yhzhje - this.money.zfbzhje - this.money.wxzfje
                if(number>=0){
                  return number.toFixed(2)
                }else{
                  return 0
                }
            },
            totalAmount () {
                let number = 0;
                for (let i in this.dataList) {
                    number += (this.dataList[i].jcjg || 0) * (this.dataList[i].number || 0) * (this.dataList[i].zk*1/100 || 0)
                    // .replace(/%/,"")
                }
                // console.log(number)
                // return number - (this.ticket?this.ticket:0);
                return number.toFixed(2)
            },
            yucun(){
              if(this.sum - this.yjje1>=0){
                return this.sum - this.yjje1
              }else{
                return 0
              }
            },
            sum () {
                // return this.money.xj*1 + this.money.zfbzhje*1 + this.money.wxzhje*1 + this.money.yhzhje*1 + this.zfyuer*1
                return this.money.xj*1 + this.money.zfbzhje*1 + this.money.wxzhje*1 + this.money.yhzhje*1
            },
            accountDisabled () {
                return this.dataList.length > 0 && this.studentid ? false : true
            }
        }
    }
</script>

<style lang="less" scoped>
.mb{
  margin-left: 50px;
}
    .index-page {
        font-size:12px;
        position: relative;

        .student1 {
          margin:10px 0;
          .input{
            width: 200px;
            margin-right:20px;
          }

        }


        .state {
            width:100%;
            margin-top:20px;
            text-align: center;

            .left,.right {
                float: left;
                width: 50%;
            }

            h3 {
                // width: 350px;
                text-align: center;
                color:#333;
            }
            .item {
                width: 350px;
                margin:10px 0;
            }

            .amount {
                font-size:30px;
                margin-top:20px;
            }

            .left span{
                display: inline-block;
                width:100px;
                text-align: right;
                coloe:#737373;
            }
            .right {
                text-align: left;
            }

            .right .item {
                width:500px;

                .title {
                    width: 300px;
                }

                .content {
                    width:150px;
                }
            }
            .right .xj {
                width:400px;
            }
        }

        .content-input {
            height:20px;
        }

        .submit {
            width:120px;
            display: block;
            margin:10px auto;
        }
        .input {
        	min-width: 120px;
        	max-width: 150px;
        }

        .item-input {
            width: 200px;
        }

        .total {
            text-align: right;
            margin:10px 0;
            span{
                margin:0 10px;
            }
        }

        .dailog .el-dialog {
            width: 70%;
        }
        article {
            margin:10px 0;

            p{
                background: #fcf4eb;
                /*padding:10px 5px;*/
            }
            input {
                border:none;
                outline: none;
                background: transparent;
                border-bottom:1px solid #ccc;
            }
            div {
                background: rgba(252,244,235,0.7);
                /*padding:10px 5px;*/
            }
            .space-between {
                padding:10px 0;
                display: block;
            }
        }

        .settlement {
            p{
                background: #fcf4eb;
            }
            div {
                background: rgba(252,244,235,0.7);
            }
        }

        .receiving-account {
            p{
                background: #F1FDFC;
            }
            div {
                background: rgba(241,253,252,0.7);
            }
        }

        .other-information {
            p{
                background: #e5e9f2;
            }
            div {
                background: rgba(229,233,242,0.7);
            }
        }
    }
</style>
